package com.example.mytips.demos;

import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

///右键>Generate>insertcode:插入代码
public class HelloInsertCode extends AnAction {

    @Override
    public void actionPerformed(AnActionEvent e) {
        ///工程
        Project project = e.getProject();
        if (project == null) return;

        ///上下文
        DataContext context = e.getDataContext();

        //编辑器
        Editor editor = CommonDataKeys.EDITOR.getData(context);
        if (editor == null) return;
        // 文档
        Document document = editor.getDocument();
        // 光标位置
        int offset = editor.getCaretModel().getOffset();

        // 从txt文件读取模板代码
        StringBuilder templateCode = readTemplateCodeFromFile("flutterTemplate/template.txt");

        ///Intellij Platform不允许在主线程中进行实时的文件写入，而需要通过一个异步任务来进行
        WriteCommandAction.runWriteCommandAction(project, new Runnable() {
            @Override
            public void run() {
                // 插入代码
                document.insertString(offset, templateCode);
            }
        });


    }

    /**
     * 读取本地的文件内容
     * @param resourcePath 放在resources/下的文件，例如template.txt
     * @return
     */
    private StringBuilder readTemplateCodeFromFile(String resourcePath) {
        StringBuilder stringBuilder = new StringBuilder();
        // 加载资源文件
        ClassLoader classLoader = HelloInsertCode.class.getClassLoader();
        InputStream inputStream = classLoader.getResourceAsStream(resourcePath);
        if (inputStream != null) {
            // 读取文件内容
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    stringBuilder.append(line).append("\n");
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            System.out.println("资源文件未找到");
        }

        return stringBuilder;
    }
}
